/** @format */

import axios from 'axios';
import { message } from '@/utils/message';

import { useGlobalLoading } from '@/hooks/useLoading';
import { onGetApi } from '@/utils/env';

console.log('onGetApi ===>', onGetApi);

const service: any = axios.create({
  baseURL: onGetApi(),
  timeout: 60000,
});
function flattenObject(obj: any, prefix = '') {
  return Object.keys(obj).reduce((acc: any, k) => {
    const pre = prefix.length ? prefix + '.' : '';
    if (typeof obj[k] === 'object') {
      Object.assign(acc, flattenObject(obj[k], pre + k));
    } else {
      acc[pre + k] = obj[k];
    }
    return acc;
  }, {});
}
service.interceptors.request.use(
  (config: any) => {
    if (config.method == 'get') {
      config.params = config.data;
    } else if (config.IsQueryString) {
      config.params = flattenObject(config.data);
      config.data = null;
    }
    config.headers['Authorization'] = uni.getStorageSync('USER_TOKEN');
    return config;
  },
  (error: any) => {
    console.log(error); // for debug
    return Promise.reject(error);
  },
);

service.interceptors.response.use(
  (response: any) => {
    console.log('response ===>', response);

    const res = response.data;

    if (res.code == 200) {
      if (response.request.responseType == 'blob') {
        if (response.headers['content-disposition']) {
          return {
            data: res,
            fileName: response.headers['content-disposition']
              ? response.headers['content-disposition'].split('filename=')[1]
              : new Date().getTime(),
          };
        } else {
          message.error('导出失败');
        }
      } else {
        return res.data;
      }
    } else if (res.code == 401) {
      useGlobalLoading().setGlobalLoading();

      uni.showModal({
        title: '您未登录',
        content: '是否现在登录？',
        confirmText: '立即登录',
        success(e) {
          if (e.confirm) {
            uni.navigateTo({
              url: '/pages/login/Index',
            });
          } else {
            uni.navigateBack({});
          }
        },
      });

      // Dialog401({
      //   onConfirm: () => {
      //     localStorage.removeItem('token');
      //     if (router.currentRoute.value.path != '/login') {
      //       if (router.currentRoute.value.fullPath == '/login') {
      //         router.replace('/login');
      //       } else {
      //         router.replace(
      //           '/login?redirect=' + router.currentRoute.value.fullPath,
      //         );
      //       }
      //     }
      //   },
      //   onCancel: () => {
      //     console.log('用户点击了取消按钮');
      //   },
      //   // redirectUrl: '/login' // 可以自定义登录页路径
      // });

      return Promise.reject(res.msg || 'Error');
    } else {
      message.error(res.msg || 'Error');
      return Promise.reject(res.msg || 'Error');
    }
  },
  (error: any) => {
    message.error(error.message || 'Error');
    return Promise.reject(error);
  },
);

service.upload = (url = '', params: any = {}, config = {}) => {
  const formData = new FormData();
  // 通过 append 向 form 对象新增数据

  const theParams: any = Object.entries(params);
  for (const [key, value] of theParams) {
    if (key === 'fileList') {
      for (const file of value) {
        formData.append('file', file);
      }
    } else {
      formData.append(key, value);
    }
  }
  return service.post(url, formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
    ...config,
  });
};

export default service;
